import VideoAdInterface from "../base/VideoAdInterface";

export default class WXVideoAd implements VideoAdInterface {

  private rewardedVideoAd = null;
  private loadFinish: boolean = false;

  private rewardCallback: (isFinish: boolean) => void;
  constructor(adID: string) {
    this.createVideoAd(adID, (err: string) => {
      if (err) {
        this.loadFinish = false
      } else {
        this.loadFinish = true;

      }
    })
  }

  isLoad() {
    return this.loadFinish;
  }


  createVideoAd(id: string, callback: Function): void {
    this.rewardedVideoAd = wx.createRewardedVideoAd({ adUnitId: id })
    if (this.rewardedVideoAd) {
      this.rewardedVideoAd.onLoad(() => {
        callback(null)
      })
      this.rewardedVideoAd.onError(err => {
        console.log(err)
        callback(err)
      })
      this.rewardedVideoAd.onClose(res => {
        // 用户点击了【关闭广告】按钮
        // 小于 2.1.0 的基础库版本，res 是一个 undefined
        if (res && res.isEnded || res === undefined) {
          // 正常播放结束，可以下发游戏奖励
          if (this.rewardCallback) {
            this.rewardCallback(true)
          }

        } else {
          // 播放中途退出，不下发游戏奖励
          if (this.rewardCallback) {
            this.rewardCallback(false);
          }

        }
      })
    }

  }

  callback(num: number) {

  }

  show(callback: (isFinish: boolean) => void): void {
    if (!this.rewardedVideoAd) {
      callback(false)
      return;
    }
    this.rewardCallback = callback;
    // this.rewardedVideoAd.show();

    this.rewardedVideoAd.show().catch(() => {
      // 失败重试
      this.rewardedVideoAd.load()
        .then(() => this.rewardedVideoAd.show())
        .catch(err => {
          console.log('激励视频 广告显示失败')
        })
    })

  }

  // 创建激励视频广告实例，提前初始化
  // let videoAd = wx.createRewardedVideoAd({
  //   adUnitId: 'adunit-193ee65e54abd18b'
  // })

  // 用户触发广告后，显示激励视频广告
  // videoAd.show().catch(() => {
  //   // 失败重试
  //   videoAd.load()
  //     .then(() => videoAd.show())
  //     .catch(err => {
  //       console.log('激励视频 广告显示失败')
  //     })
  // })  
}
